using MeterReader.WebApi.Models;
using MeterReader.WebApi.Services;
using MeterReader.WebApi.Services.Repositories;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Options;
using NLog.Extensions.Logging;

namespace MeterReader.WebApi
{
    public class Program
    {
        public static void Main(string[] args)
        {
            var builder = WebApplication.CreateBuilder(args);

            // Add services to the container.
            var services = builder.Services;
            ConfigrationCollection(services);
            var app = builder.Build();
            using (var scope = app.Services.CreateScope())
            {
                var newDatabase = scope.ServiceProvider.GetRequiredService<MyDbContext>();
                newDatabase.Database.EnsureCreated();
            }

            // Configure the HTTP request pipeline.
            if (app.Environment.IsDevelopment())
            {
                app.UseSwagger();
                app.UseSwaggerUI();
            }

            app.UseHttpsRedirection();

            app.UseAuthorization();

            app.MapControllers();

            app.Run();
        }

        private static void ConfigrationCollection(IServiceCollection services)
        {
            var root = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
                .Build();
            services.AddControllers().AddJsonOptions(o => o.JsonSerializerOptions.PropertyNamingPolicy = null);
            services
                .AddEndpointsApiExplorer()
                .AddSwaggerGen()
                .AddLogging(b => b.AddNLog())
                .AddOptions()
                .Configure<Database>(database => root.GetSection("Database").Bind(database))
                .Configure<MeterCountConfig>(count => root.GetSection("Database:MeterCount").Bind(count))
                .AddDbContext<MyDbContext>((services, options) =>
                    options.UseSqlite(services.GetRequiredService<IOptionsSnapshot<Database>>().Value.ConnectionString)
                )
                .AddScoped<IRepository, Repository>(services => new Repository(
                    services.GetRequiredService<MyDbContext>(),
                    services.GetRequiredService<IOptionsSnapshot<Database>>().Value.Count
                ))
                .AddScoped<IDataService, DataService>();
        }
    }
}
